package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.service.UserFollowsService;
import com.example.demo.service.UserService;
import com.example.demo.util.HashUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import io.swagger.v3.oas.annotations.Parameter;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private COSClient cosClient;
    @Autowired
    private UserFollowsController userFollowsController;
    @Autowired
    private UserFollowsService userFollowsService;

    @Value("${tencent.cos.bucket-name}")
    private String bucketName;

    @PostMapping("/login")
    public Map<String, Object> login(@Parameter(description = "账号", required = true) @RequestParam String account,
                                     @Parameter(description = "密码", required = true) @RequestParam String password,
                                     HttpServletResponse response, //设置响应对象
                                      HttpServletRequest request
    ) {
        //调用服务层方法进行登陆验证
        User user = userService.login(account, password);
        if (user != null) {
            HttpSession session = request.getSession();
            session.setAttribute("user", user); // 将用户信息存储在 Session 中
            session.setMaxInactiveInterval(60 * 60 * 24 * 7); // 设置 Session 有效期为 7 天
            Cookie cookie = new Cookie("userToken", user.getId().toString());
            cookie.setPath("/");
            // cookie.setHttpOnly(true);
            cookie.setMaxAge(60 * 60 * 24 * 7);
            response.addCookie(cookie);
            // 打印 Cookie 信息
//             System.out.println("Cookie 已生成: " + cookie.getName() + "=" + cookie.getValue());

            //登陆成功，返回用户信息
            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("message", "success");
            result.put("user", user);
            return result;
        } else {
            //登陆失败
            return Map.of("code", 401, "message", "账号或密码错误");
        }
    }

    @PostMapping("/register")
    public Map<String, Object> register(@Parameter(description = "账号", required = true) @RequestParam String account,
                                        @Parameter(description = "密码", required = true) @RequestParam String password,
                                        @Parameter(description = "邮箱", required = true) @RequestParam String email) {
        //创建用户对象
        User user = new User();
        user.setAccount(account);
        user.setUsername(account);
        user.setPassword(password);
        user.setEmail(email);

        //调用服务层方法注册用户
        try {
            boolean isSuccess = userService.register(user);
            if (isSuccess) {
                return Map.of("code", 200, "message", "success");
            } else {
                return Map.of("code", 500, "message", "failure");
            }
        } catch (Exception e) {
            return Map.of("code", 400, "message", e.getMessage());
        }
    }
@GetMapping("/currentUser")
public Map<String, Object> getCurrentUser(HttpServletRequest request) {
    // 获取当前用户的 Cookie
    String userToken = getCookieValue(request, "userToken");
    if (userToken == null) {
        return Map.of("code", 401, "message", "用户未登录");
    }

    // 根据 userToken（用户 ID）查询用户信息
    Long userId = Long.parseLong(userToken);
    User user = userService.findById(userId);
    if (user == null) {
        return Map.of("code", 404, "message", "用户不存在");
    }

    // 调用 UserFollowsController 中的接口，获取关注者数量、关注者列表、当前用户关注的人的数量和列表
    Map<String, Object> followerCountResponse = userFollowsController.getFollowerCount(userId.intValue());
    Map<String, Object> followersResponse = userFollowsController.getFollowers(userId);
    Map<String, Object> followedCountResponse = userFollowsController.getFollowedCount(request);
    Map<String, Object> followedUsersResponse = userFollowsController.getFollowedUsers(request);

    // 构建返回结果
    Map<String, Object> result = new HashMap<>();
    result.put("code", 200);
    result.put("message", "success");
    result.put("user", user);
    result.put("followerCount", followerCountResponse.get("data")); // 关注者数量
    result.put("followers", followersResponse.get("data")); // 关注者列表
    result.put("followedCount", followedCountResponse.get("data")); // 当前用户关注的人的数量
    result.put("followedUsers", followedUsersResponse.get("data")); // 当前用户关注的人的列表

    return result;
}

    // 获取指定 Cookie 的值
    private String getCookieValue(HttpServletRequest request, String cookieName) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(cookieName)) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }
//修改密码
    @PostMapping("/changePassword")
    public Map<String,Object> changePassword(
            @Parameter(description = "旧密码",required = true) @RequestParam String oldPassword,
            @Parameter(description = "新密码",required = true) @RequestParam String newPassword,
            HttpServletResponse response,
            HttpServletRequest request
    ){
        //获取当前用户的cookie
        String usertoken = getCookieValue(request, "userToken");
        if (usertoken == null) {
            return Map.of("code",401,"message","用户未登录");
        }
        //根据userToken查询用户信息
        Long userId = Long.parseLong(usertoken);
        User user  = userService.findById(userId);
        System.out.println("userID:"+userId+"userToken:"+usertoken);
        if(user == null) {
            return Map.of("code", 404, "message", "用户不存在");
        }
        //验证旧密码是否正确
        boolean isOlePassword = HashUtil.verifyPassword(oldPassword,user.getPassword());
        if(!isOlePassword) {
            return Map.of("code", 400, "message", "旧密码错误");
        }
        //更新密码
        boolean isPasswordUpdate = userService.updatePassword(userId,newPassword);
        if(isPasswordUpdate) {
            //清除浏览器端的cookie
            Cookie sessionCookie = new Cookie("userToken",null);
            sessionCookie.setMaxAge(0);
            sessionCookie.setPath("/");
            response.addCookie(sessionCookie);
            return Map.of("code", 200, "message", "密码修改成功，请重新登录");
        }else {
            return Map.of("code", 500, "message", "密码修改失败，请稍后重试");
        }
    }
    @PutMapping("/updateInfo")
    public Map<String, Object> updateInfo(
            HttpServletRequest request,
            @RequestBody User user
    ) {
        // 获取当前用户信息
        Map<String, Object> currentUserResponse = getCurrentUser(request);
        if (currentUserResponse.get("code").equals(401) || currentUserResponse.get("code").equals(404)) {
            return currentUserResponse; // 返回未登录或用户不存在的错误信息
        }

        // 获取当前用户 ID
        User currentUser = (User) currentUserResponse.get("user");
        Long userId = currentUser.getId();
        System.out.println(userId);

        // 检查至少有一个字段需要更新
        if (user.getUsername() == null && user.getAvatar() == null &&
                user.getGender() == null && user.getBirthday() == null &&
                user.getBio() == null) {
            return Map.of("code", 400, "message", "至少需要更新一个字段");
        }

        // 调用服务层更新用户信息
        boolean isUpdated = userService.updateUserInfo(userId, user);
        if (isUpdated) {
            return Map.of("code", 200, "message", "用户信息更新成功");
        } else {
            return Map.of("code", 500, "message", "用户信息更新失败");
        }
    }
    @PostMapping("/updateUserAvatar")
    public Map<String, Object> updateUserAvatar(
            @RequestParam("file") MultipartFile file,
            HttpServletRequest request) {
        // 获取当前用户信息
        Map<String, Object> currentUserResponse = getCurrentUser(request);
        if (currentUserResponse.get("code").equals(401) || currentUserResponse.get("code").equals(404)) {
            return Map.of("code", currentUserResponse.get("code"), "message", currentUserResponse.get("message"));
        }
        // 获取当前用户ID
        User currentUser = (User) currentUserResponse.get("user");
        Long userId = currentUser.getId();
        // 检查文件是否为空
        if (file.isEmpty()) {
            return Map.of("code", 400, "message", "文件不能为空");
        }
        // 检查文件类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            return Map.of("code", 400, "message", "请输入图片文件");
        }
        // 检查文件大小
        if (file.getSize() > 5 * 1024 * 1024) {
            return Map.of("code", 400, "message", "文件大小不能超过5MB");
        }
        // 生成文件名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename != null ? originalFilename.substring(originalFilename.lastIndexOf(".")) : "";
        String fileName = UUID.randomUUID() + fileExtension;
        // 保存文件到腾讯云 COS
        try {
            // 将 MultipartFile 转换为临时文件
            Path tempFilePath = Paths.get(System.getProperty("java.io.tmpdir"), fileName);
            file.transferTo(tempFilePath.toFile());
            // 上传到腾讯云 COS
            String cosKey = "avatar_image/" + fileName; // 指定 COS 中的路径
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, cosKey, tempFilePath.toFile());
            cosClient.putObject(putObjectRequest);
            // 设置 Content-Type
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType("image/gif"); // 根据文件类型设置
            putObjectRequest.setMetadata(metadata);
            cosClient.putObject(putObjectRequest);
            // 删除临时文件
            Files.delete(tempFilePath);
            // 生成文件访问 URL
            String avatarUrl = "https://" + bucketName + ".cos." + cosClient.getClientConfig().getRegion().getRegionName() + ".myqcloud.com/" + cosKey;
            // 更新用户头像 URL
            userService.updateUserAvatar(userId, avatarUrl);
            return Map.of("code", 200, "message", "success", "avatar", avatarUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return Map.of("code", 500, "message", "文件上传失败: " + e.getMessage());
        }
    }
    // 获取当前用户的粉丝数量
    @GetMapping("/currentUser/followers/count")
    public Map<String, Object> getCurrentUserFollowerCount(HttpServletRequest request) {
        // 获取当前用户信息
        Map<String, Object> currentUserResponse = getCurrentUser(request);
        if (currentUserResponse.get("code").equals(401) || currentUserResponse.get("code").equals(404)) {
            return currentUserResponse; // 返回未登录或用户不存在的错误信息
        }

        // 获取当前用户 ID
        User currentUser = (User) currentUserResponse.get("user");
        Long userId = currentUser.getId();

        // 调用 UserService 的 getFollowerCount 方法
        int followerCount = userService.getFollowerCount(userId);
        return Map.of("code", 200, "message", "success", "data", followerCount);
    }
    @GetMapping("/userInfo")
    public Map<String, Object> getUserInfo(
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) String username
    ) {
        // 参数校验：userId 和 username 不能同时为空
        if (userId == null && username == null) {
            return Map.of("code", 400, "message", "参数错误：userId 和 username 不能同时为空");
        }

        // 根据 userId 或 username 查询用户信息
        List<User> users;
        if (userId != null) {
            // 根据 userId 查询单个用户
            User user = userService.findById(userId);
            if (user == null) {
                return Map.of("code", 404, "message", "用户不存在");
            }
            users = List.of(user); // 将单个用户包装为列表
        } else {
            // 根据 username 模糊查询用户列表
            users = userService.findByUsername(username);
            if (users.isEmpty()) {
                return Map.of("code", 404, "message", "用户不存在");
            }
        }

        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("message", "success");

        // 将用户列表放入结果中
        result.put("users", users);

        // 如果查询到单个用户，返回该用户的详细信息
        if (users.size() == 1) {
            User user = users.get(0);

            // 获取关注者数量、关注者列表、当前用户关注的人的数量和列表
            int followerCount = userFollowsService.getFollowerCount(user.getId().intValue());
            List<User> followers = userFollowsService.getFollowers(user.getId());
            int followedCount = userFollowsService.getFollowedCount(user.getId().intValue());
            List<User> followedUsers = userFollowsService.getFollowedUsers(user.getId());

            result.put("followerCount", followerCount); // 关注者数量
            result.put("followers", followers); // 关注者列表
            result.put("followedCount", followedCount); // 当前用户关注的人的数量
            result.put("followedUsers", followedUsers); // 当前用户关注的人的列表
        }

        return result;
    }
}
